//
//  144. 二叉树的前序遍历.swift
//  Top600
//
//  Created by rjb on 2021/7/27.
//

import Foundation
public class TreeNode {
    public var val:Int
    public var left:TreeNode?
    public var right:TreeNode?
    public init () {
        self.val = 0
        self.left = nil
        self.right = nil
    }
    public init(_ val:Int) {
        self.val = val
        self.left = nil
        self.right = nil
    }
    public init(_ val:Int,_ left:TreeNode?,_ right:TreeNode? ) {
        self.val = val
        self.left = left
        self.right = right
    }
}

class Solution144 {
    func preorderTraversal(_ root: TreeNode?) -> [Int] {
        var result: [Int] = []
        preOrder(root, result: &result)
        return result
    }
    func preOrder(_ root: TreeNode?, result: inout [Int]) {
        guard let root = root else {
            return
        }
        result.append(root.val)
        preOrder(root.left, result: &result)
        preOrder(root.right, result: &result)
    }
    static func test() {
        let solution = Solution144()
        let node1 = TreeNode(1)
        let node2 = TreeNode(2)
        let node3 = TreeNode(3)
        node1.right = node2
        node2.left = node3
        let result = solution.preorderTraversal(node1)
        print(result)
    }
}
